package com.onjob.security;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import util.dao.HibernateDaoImpl;

public class GroupsDaoImpl extends HibernateDaoImpl<Groups,Long> implements GroupsDao {

	@Override
	 @Transactional(propagation=Propagation.REQUIRED)
	public boolean isCanDo(Users user, String url) {
		// TODO Auto-generated method stub
		Long var = null;
		Iterator<Groups> it=user.getGroupsId().iterator();
    	while(it.hasNext()){
    		var=it.next().getId();
    	}
    	System.err.println("var================== "+var);
    	int j=Groups.getUrlMap().get(var).size();
    	List<String> urlList = Groups.getUrlMap().get(var);
        System.err.println(urlList.size());
	    for(int i=0;i<j;i++){
	    	System.err.println(urlList.get(i));
	    	  if(urlList.get(i).equals(url)){
	    		  return true;
	    	  }
	       }
		return false;
	}

	@Override
	public Groups findByName(String name) {
		
		Session session = null;
		session = this.getSession();
		Query query = session.createQuery("from "+ Groups.class.getName()+" where groupName=?");
		query.setString(0, name);
		return (Groups)query.uniqueResult();
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<String> findAuthoritys(Users user) {
		Session session = null;
		session = this.getSession();
	    Query query = session.createSQLQuery("SELECT f.functionUrl FROM onjob.`function` f ," +
	    		" onjob.groups g,onjob.users_groups ug,onjob.groups_function gf where gf.functionId=f.id" +
	    		" and gf.groupsId=g.id and ug.groupsId=g.id and ug.usersId="+user.getId()+"");
	       List<String> urlList = query.list();
//	       for(int i=0;i<urlList.size();i++){
//	    	   System.err.println(urlList.get(i));
//	       }
		return urlList;
	}

	@Override
	public Groups findByUserId(Long uid) {
		
		Groups groups=null;
		Session session = null;
		session = this.getSession();
		Query query = session.createQuery("from "+Users.class.getName()+" where id="+uid+"");
		Users users = new Users();
		users = (Users)query.uniqueResult();
		Set<Groups> gs = new HashSet<Groups>();
		gs = users.getGroupsId();
		Iterator<Groups> it = gs.iterator();
		while(it.hasNext()){
			groups = it.next();
		}
		return groups;
	}

	

	


}
